package de.koller.zero.view;

import de.koller.zero.ZeroRoot;
import de.koller.zero.engine.commands.RemoveNode;
import de.koller.zero.model.Player;
import de.koller.zero.view.builder.PlayerListComp;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

public class PlayerListFrame extends ZFrameNode {

	private final PlayerListComp comp = new PlayerListComp( this );
	
	@Override
	public void generate( ZeroRoot root, Object... references ) {
		super.generate( root, references );
		
		comp.refresh.addActionListener( new RefreshListener() );
		
		frame.add( comp );
		frame.pack();
	}
	
	@Override protected void frameClosed() {
		this.root.gui.call( new RemoveNode( this ) );
	}

	@Override
	protected Rectangle getLocation() {
		return new Rectangle( 200, 100, 100, 100 );
	}

	@Override
	protected String getTitle() {
		return "Spielerliste";
	}
	
	public TableModel create() {
		return new PlayerTM();
	}
	
	private class RefreshListener implements ActionListener {

		@Override
		public void actionPerformed( ActionEvent e ) {
			comp.playertable.setModel( new PlayerTM( true ) );
		}
		
	}
	
	private class PlayerTM implements TableModel {

		private List<Player> copied = new ArrayList<>();
		
		private PlayerTM() {

		}
		
		private PlayerTM( boolean use ) {
			copied.addAll( root.realm.getPlayers() );
			Collections.sort( copied, new PlayerNameSort() );
		}
		
		@Override
		public void addTableModelListener( TableModelListener l ) {
			
		}

		@Override
		public Class<?> getColumnClass( int columnIndex ) {
			return String.class;
		}

		@Override
		public int getColumnCount() {
			return 1;
		}

		@Override
		public String getColumnName( int columnIndex ) {
			return "Spielername";
		}

		@Override
		public int getRowCount() {
			return copied.size();
		}

		@Override
		public Object getValueAt( int rowIndex, int columnIndex ) {
			return copied.get( rowIndex ).name;
		}

		@Override
		public boolean isCellEditable( int rowIndex, int columnIndex ) {
			return false;
		}

		@Override
		public void removeTableModelListener( TableModelListener l ) {
			
		}

		@Override
		public void setValueAt( Object aValue, int rowIndex, int columnIndex ) {
			
		}
		
	}
	
	private class PlayerNameSort implements Comparator<Player> {

		@Override
		public int compare( Player o1, Player o2 ) {
			return o1.name.compareTo( o2.name );
		}
		
	}
	
}
